
class CartsController < ApplicationController
  before_action :find_cart, only: [:update, :destroy]

  def index
    fetch_home_data
  end

  def get_data
    basic = Cart.by_user_uuid(session[:user_uuid]).includes([:product => [:main_product_image]]).order("id desc")
    limit = params[:limit]
    @carts = limit.present? ? basic.limit(limit) : basic
    render json: CartService.wrap_carts_with_product_and_channel(@carts)
 end

  def create
    amount = params[:amount].to_i
    amount = amount <= 0 ? 1 : amount

    @product = Product.find(params[:product_id])
    @cart = Cart.create_or_update!({
      user_uuid: session[:user_uuid],
      product_id: params[:product_id],
      amount: amount
    })

    if mobile?
      render json: { cart: @cart }
    else
      render layout: false
    end
  end

  def update
    #check sku
    product = Product.find(params[:product_id])
    amount = params[:amount].to_i
    amount = amount <= 0 ? 1 : amount

    if amount > product.amount
      render_fail("该商品库存不足")
    elsif @cart.update_attribute :amount, amount
      render_success("更新购物车成功")
    else
      render_fail("更新购物车失败")
    end
  end

  def destroy
    begin
      @cart.destroy!
      render_success("购物车删除成功")
    rescue
      render_success("购物车删除失败")
    end
  end

  def batch_destroy
    @carts = Cart.find(params[:ids])
    begin
      @carts.each(&:destroy!)
      render_success("购物车删除成功")
    rescue
      render_fail("购物车删除失败")
    end
  end

  private

  def find_cart
    @cart = Cart.by_user_uuid(session[:user_uuid])
      .where(id: params[:id]).first
    if @cart.nil?
      false
    else
    end
  end


end
